<template>
  <div class="banner-add">
    <div class="createPost-main-container">
      <el-form ref="form" label-width="120px" :rules="rules" :model="form">

        <el-form-item label="产品名称" prop="name">
          <el-input v-model="form.name" type="text" maxlength="60" show-word-limit />
        </el-form-item>

        <el-form-item label="所属类目" prop="categoryId">
          <el-select v-model="form.categoryId" clearable class="filter-item" placeholder="选择所属类目">
            <el-option v-for="(item, idx) in categoryList" :key="idx" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item label="选择产品图片" prop="picture">
          <upload :data="picture" />
        </el-form-item>

        <!-- <el-form-item label="购买链接">
          <el-input v-model="form.buyLink" />
        </el-form-item> -->
        <el-form-item label="购买链接">
          <div>
            <div class="template-table-con">
              <div class="template-table-con_left title">平台名</div>
              <div class="template-table-con_left title">文字颜色</div>
              <div class="template-table-con_right title">购买链接</div>
              <div @click="addBuyLink2()">
                <el-button
                  type="text"
                  size="mini"
                >增加</el-button>
              </div>
            </div>
            <div v-for="(link,index) in form.buyLink" :key="index" class="template-table-con">
              <div class="template-table-con_left">
                <el-input
                  v-model="link.name"
                  size="mini"
                  clearable
                  placeholder="平台名"
                />
              </div>
              <div>
                <el-color-picker v-model="link.buyPlatformColor" />
              </div>
              <div class="template-table-con_right">
                <el-input
                  v-model="link.link"
                  size="mini"
                  clearable
                  placeholder="购买链接"
                />
              </div>
              <div style="margin-left: 10px;" @click="deleteBuyLink2(index)">
                <i class="el-icon-delete" />
              </div>
            </div>
          </div>
        </el-form-item>

        <aside>产品详情配置</aside>

        <div v-for="(item, idx) in content" :key="idx">
          <el-card class="box-card logo-card">
            <div slot="header" class="clearfix">
              <span>序号：{{ idx + 1 }}</span>
              <el-button style="float: right; padding: 3px 0; margin-left: 10px;" type="text" @click="deletCard(idx)">删除</el-button>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                :disabled="idx == content.length - 1"
                @click="moveDown(idx)"
              >下移</el-button>
              <el-button
                style="float: right; padding: 3px 0"
                type="text"
                :disabled="idx == 0"
                @click="moveUp(idx)"
              >上移</el-button>
            </div>
            <div class="text item">
              <el-form-item label="跳转类型" prop="activityType">
                <el-radio-group v-model="item.activityType" size="mini" @change="resetActivityType(idx)">
                  <el-radio label="PRODUCT" border>产品</el-radio>
                  <el-radio label="NEWS_DETAIL" border>资讯</el-radio>
                  <el-radio label="OTHER" border>其它</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="页面布局" required>
                <el-radio-group v-model="item.style.detailsLayout" size="mini">
                  <el-radio v-for="(style, index) in styleList" :key="index" class="ui-mb-10" :label="style.value" border>{{ style.text }}</el-radio>
                </el-radio-group>
              </el-form-item>

              <el-form-item v-show="item.style.detailsLayout!=='PIC_NO' && item.style.detailsLayout!=='VIDEO_ALL'" label="选择图片">
                <upload :data="item.imgData" />
              </el-form-item>

              <el-form-item v-show="item.style.detailsLayout!=='PIC_NO' && item.style.detailsLayout!=='VIDEO_ALL'" label="选择竖版图片">
                <upload :data="item.imgData2" />
              </el-form-item>

              <div v-show="item.style.detailsLayout==='VIDEO_ALL'">
                <el-form-item label="上传视频">
                  <el-button
                    style="margin-left: 10px;"
                    type="info"
                    plain
                    size="mini"
                    @click="uploadVideoBtn(idx)"
                  >
                    上传
                  </el-button>
                </el-form-item>
                <el-form-item v-show="item.videoContent" label="视频预览">
                  <div v-html="item.videoContent" />
                </el-form-item>
              </div>

              <el-form-item label="上边距">
                <el-input v-model="item.marginTop" />
              </el-form-item>

              <el-form-item label="下边距">
                <el-input v-model="item.marginBottom" />
              </el-form-item>

              <div v-show="item.style.detailsLayout!=='PIC_ALL' && item.style.detailsLayout!=='VIDEO_ALL'">
                <el-form-item label="标题">
                  <el-input v-model="item.title" type="text" maxlength="60" show-word-limit />
                </el-form-item>

                <el-form-item label="标题文字颜色">
                  <el-color-picker v-model="item.style.titleColor" />
                </el-form-item>

                <el-form-item label="副标题">
                  <el-input v-model="item.subTitle" type="text" maxlength="60" show-word-limit />
                </el-form-item>

                <el-form-item label="副标题文字颜色">
                  <el-color-picker v-model="item.style.subTitleColor" />
                </el-form-item>

                <el-form-item label="详情描述">
                  <el-input v-model="item.description" type="text" maxlength="200" show-word-limit />
                </el-form-item>

                <el-form-item label="描述文字颜色">
                  <el-color-picker v-model="item.style.descriptionColor" />
                </el-form-item>

                <el-form-item v-if="item.activityType=='PRODUCT'" label="跳转链接">
                  <el-select v-model="item.detailLink" clearable filterable placeholder="跳转详情">
                    <el-option
                      v-for="link in productLink"
                      :key="link.id"
                      :label="link.name"
                      :value="link.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item v-if="item.activityType=='NEWS_DETAIL'" label="跳转链接">
                  <el-select v-model="item.detailLink" clearable filterable placeholder="跳转详情">
                    <el-option
                      v-for="link in newsLink"
                      :key="link.id"
                      :label="link.title"
                      :value="link.id"
                    />
                  </el-select>
                </el-form-item>
                <el-form-item v-if="item.activityType=='OTHER'" label="跳转链接">
                  <el-input v-model="item.detailLink" />
                </el-form-item>

                <!-- <el-form-item v-if="item.activityType=='PRODUCT'" label="购买链接">
                  <el-input v-model="item.buyLink" />
                </el-form-item> -->

                <el-form-item v-if="item.activityType=='PRODUCT'" label="购买链接">
                  <div>
                    <div class="template-table-con">
                      <div class="template-table-con_left title">平台名</div>
                      <div class="template-table-con_left title">文字颜色</div>
                      <div class="template-table-con_right title">购买链接</div>
                      <div @click="addBuyLink(idx)">
                        <el-button
                          type="text"
                          size="mini"
                        >增加</el-button>
                      </div>
                    </div>
                    <div v-for="(link,index) in item.buyLink" :key="index" class="template-table-con">
                      <div class="template-table-con_left">
                        <el-input
                          v-model="link.name"
                          size="mini"
                          clearable
                          placeholder="平台名"
                        />
                      </div>
                      <div>
                        <el-color-picker v-model="link.buyPlatformColor" />
                      </div>
                      <div class="template-table-con_right">
                        <el-input
                          v-model="link.link"
                          size="mini"
                          clearable
                          placeholder="购买链接"
                        />
                      </div>
                      <div style="margin-left: 10px;" @click="deleteBuyLink(idx, index)">
                        <i class="el-icon-delete" />
                      </div>
                    </div>
                  </div>
                </el-form-item>
              </div>
            </div>
          </el-card>
        </div>

        <el-form-item>
          <el-button
            :loading="ajaxStatus"
            style="margin-left: 10px;"
            type="primary"
            plain
            @click="addCard"
          >
            增加
          </el-button>
        </el-form-item>

        <aside>产品规格配置</aside>

        <div v-for="(SpecItem, specIdx) in productSpecs" :key="SpecItem.id">
          <el-card class="box-card logo-card">
            <div slot="header" class="clearfix">
              <span>序号：{{ specIdx + 1 }}</span>
              <el-button style="float: right; padding: 3px 0" type="text" @click="deletLabel(specIdx)">删除</el-button>
            </div>
            <div class="text item">
              <el-form-item label="规格名称" prop="categoryId">
                <el-select v-model="SpecItem.labelId" clearable class="filter-item" placeholder="选择规格名称">
                  <el-option v-for="(spec, index) in specLabel" :key="index" :label="spec.name" :value="spec.id" />
                </el-select>
              </el-form-item>
              <el-form-item label="规格详情">
                <el-input v-model="SpecItem.text" :rows="5" type="textarea" />
              </el-form-item>
              <el-form-item label="规格描述">
                <el-input v-model="SpecItem.desc" :rows="5" type="textarea" />
              </el-form-item>
              <el-form-item label="选择图片">
                <upload :data="SpecItem.pictureUrl" />
              </el-form-item>
              <el-form-item label="搜索误差值">
                <el-input v-model="SpecItem.alw" type="number" />
              </el-form-item>
            </div>
          </el-card>
        </div>

        <el-form-item>
          <el-button
            :loading="ajaxStatus"
            style="margin-left: 10px;"
            type="primary"
            plain
            @click="addLabel"
          >
            增加
          </el-button>
        </el-form-item>

      </el-form>
    </div>

    <sticky :class-name="'cms-sub-navbar '+ajaxStatus">
      <el-button :loading="ajaxStatus" style="margin-left: 10px;" type="success" @click="submitForm('1')">
        发布
      </el-button>
      <el-button :loading="ajaxStatus" @click="reset()">
        取消
      </el-button>
    </sticky>

    <el-dialog title="上传视频" :visible.sync="uploadVideo">
      <div style="line-height: 1; margin-bottom: 20px;">
        <el-alert
          title="请先上传视频封面图片"
          type="info"
          description="封面图片仅支持jpg/png格式，视频暂时仅支持mp4格式"
          show-icon
          :closable="false"
        />
      </div>
      <upload :data="videoImgData" />
      <div slot="footer" class="dialog-footer">
        <el-button :loading="uploading" @click="uploadVideo = false">取 消</el-button>
        <el-button
          :loading="uploading"
          type="primary"
          :disabled="!videoImgData.imgUrl"
          @click="uploadfile"
        >上传视频</el-button>
      </div>
    </el-dialog>

    <input
      :id="'videoIdx' + tabName"
      ref="inputer"
      type="file"
      name="file"
      style="display:none"
      @change="handleFileChange"
      @touchstart="handleFileChange"
    >

  </div>
</template>

<script>
import { postData, getEditData, getCategoryList, getSpecLabel } from '@/api/product/detail'
import { getProductLink, getNewsLink } from '@/api/common'
import Sticky from 'components/Sticky'
import Upload from 'components/Upload/img-upload'
import { uploadFile } from 'api/common'

const defaultForm = {
  name: '',
  categoryId: '',
  picture: '',
  content: [],
  buyLink: [{
    name: '',
    buyPlatformColor: '#000',
    link: ''
  }],
  productSpecs: []
}

const styleList = [
  { value: 'PIC_LEFT', text: '左图右文' },
  { value: 'PIC_RIGHT', text: '右图左文' },
  { value: 'PIC_UP', text: '上图下文' },
  { value: 'PIC_BOTTOM', text: '下图上文' },
  { value: 'PIC_NO', text: '全文' },
  { value: 'PIC_ALL', text: '全图' },
  { value: 'VIDEO_ALL', text: '视频' }
]

export default {
  components: { Sticky, Upload },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    tabName: {
      type: String,
      default: ''
    }
  },
  data() {
    const checkImg = (rule, value, callback) => {
      if (!this.picture.imgUrl) {
        return callback(new Error('请上传图片'))
      }
      callback()
    }
    return {
      ajaxStatus: false,
      form: Object.assign({}, defaultForm),

      uploadVideo: false,
      uploading: false,
      flagIdx: '',
      videoImgData: {
        myId: Math.random(),
        path: 'news',
        imgUrl: '',
        ImgSize: 10000,
        text: '视频封面图片大小不得超过300k'
      },

      picture: {
        myId: Math.random(),
        path: 'product',
        imgUrl: '',
        ImgSize: 10000,
        text: '图片推荐比例：80*80，大小不得超过500K，支持png/jpg格式'
      },
      content: [{
        title: '',
        activityType: 'PRODUCT',
        subTitle: '',
        imgData: {
          myId: Math.random(),
          path: 'product',
          imgUrl: '',
          ImgSize: 10000,
          text: '图片大小不得超过10000K，支持png/jpg格式'
        },
        imgData2: {
          myId: Math.random(),
          path: 'product',
          imgUrl: '',
          ImgSize: 10000,
          text: '图片大小不得超过10000K，支持png/jpg格式'
        },
        imageUrl: '',
        phoneImg: '',
        videoUrl: '',
        description: '',
        detailLink: '',
        marginTop: 0,
        marginBottom: 0,
        buyLink: [{
          name: '',
          buyPlatformColor: '#000',
          link: ''
        }],
        style: {
          detailsLayout: 'PIC_LEFT',
          status: 1,
          styleName: '',
          titleColor: '#000',
          subTitleColor: '#000',
          descriptionColor: '#000'
        }
      }],
      productSpecs: [{
        alw: 0,
        labelId: '',
        text: '',
        desc: '',
        picture: '',
        pictureUrl: {
          myId: Math.random(),
          path: 'product',
          imgUrl: '',
          ImgSize: 10000,
          text: '图片大小不得超过10000K，支持png/jpg格式'
        }
      }],
      categoryList: [],
      specLabel: [],
      styleList,

      productLink: [],
      newsLink: [],

      videoForm: {
        file: null,
        path: 'home'
      },

      rules: {
        name: { required: true, message: '请输入小于60个字的标题', trigger: 'blur', min: 1, max: 60 },
        categoryId: { required: true, message: '请选择所属类目', trigger: 'blur' },
        picture: { required: true, validator: checkImg }
      }
    }
  },
  computed: {
  },
  created() {
    this.getLinkList()
    this.getCategoryList()
    this.getSpecLabel()
    if (this.isEdit) {
      const id = this.$route.query && this.$route.query.id
      this.fetchData(id)
    }
  },
  methods: {
    getLinkList() {
      getProductLink().then(e => {
        this.productLink = e.data
      })
      getNewsLink().then(e => {
        this.newsLink = e.data
      })
    },
    addCard() {
      const index = this.content.length + 1
      this.content.push({
        title: '',
        subTitle: '',
        activityType: 'PRODUCT',
        imgData: {
          myId: Math.random(),
          path: 'product',
          imgUrl: '',
          ImgSize: 10000,
          text: '图片大小不得超过10000K，支持png/jpg格式'
        },
        imgData2: {
          myId: Math.random(),
          path: 'product',
          imgUrl: '',
          ImgSize: 10000,
          text: '图片大小不得超过10000K，支持png/jpg格式'
        },
        imageUrl: '',
        phoneImg: '',
        description: '',
        detailLink: '',
        marginTop: 0,
        marginBottom: 0,
        buyLink: [{
          name: '',
          buyPlatformColor: '#000',
          link: ''
        }],
        style: {
          detailsLayout: 'PIC_LEFT',
          status: 1,
          styleName: `实例${index}`,
          titleColor: '#000',
          subTitleColor: '#000',
          descriptionColor: '#000'
        }
      })
    },
    deletCard(idx) {
      this.content.splice(idx, 1)
    },
    addLabel() {
      this.productSpecs.push({
        alw: 0,
        labelId: '',
        text: '',
        desc: '',
        picture: '',
        videoContent: '',
        videoUrl: '',
        pictureUrl: {
          myId: Math.random(),
          path: 'product',
          imgUrl: '',
          ImgSize: 10000,
          text: '图片大小不得超过10000K，支持png/jpg格式'
        }
      })
    },
    deletLabel(idx) {
      this.productSpecs.splice(idx, 1)
    },

    addBuyLink2() {
      const item = {
        name: '',
        buyPlatformColor: '#000',
        link: ''
      }
      this.form.buyLink.push(item)
    },

    deleteBuyLink2(index) {
      this.form.buyLink.splice(index, 1)
    },

    addBuyLink(idx) {
      const item = {
        name: '',
        buyPlatformColor: '#000',
        link: ''
      }
      this.content[idx].buyLink.push(item)
    },

    deleteBuyLink(idx, index) {
      this.content[idx].buyLink.splice(index, 1)
    },

    uploadVideoBtn(idx) {
      this.uploadVideo = true
      this.flagIdx = idx
    },

    // 上传文件 图片/视频
    handleFileChange() {
      if (this.uploading) {
        return
      }
      const inputDOM = this.$refs.inputer
      const file = inputDOM.files[0]
      // 判断是否是图片上传
      const imageType = /image.*/
      const isImage = file.type.match(imageType)
      this.checkImg(file, isImage).then(() => {
        this.uploading = true
        const formData = new window.FormData()
        Object.keys(this.videoForm).forEach((y) => {
          formData.append(y, this.videoForm[y])
        })
        formData.append('file', file)
        uploadFile(formData).then((re) => {
          this.uploading = false
          const { data } = re
          this.content[this.flagIdx].imageUrl = this.videoImgData.imgUrl
          this.content[this.flagIdx].videoUrl = data
          this.content[this.flagIdx].videoContent = `<div>
                    <video
                      controls
                      x5-playsinline playsinline webkit-playsinline
                      poster="/${this.videoImgData.imgUrl}"
                      class="video_upload_con"
                      object-fit: fill" >
                        <source src="${data}" type="video/mp4" />
  		                  您的浏览器不支持video标签播放视频
                    </video>
                </div>`
          this.uploadVideo = false
          this.$refs.inputer.value = ''
          this.videoImgData.imgUrl = ''
        })
      })
    },

    moveUp(index) {
      if (index < 1) {
        return
      }
      // 重制排序
      const upData = this.content[index - 1]
      this.content.splice(index - 1, 1)
      this.content.splice(index, 0, upData)
    },

    // 下移
    moveDown(index) {
      // 重制排序
      const upData = this.content[index + 1]
      this.content.splice(index + 1, 1)
      this.content.splice(index, 0, upData)
    },

    // 获取上传图片宽高
    checkImg(file) {
      return new Promise((resolve, reject) => {
        if (file.type.includes('video')) {
          const isMP4 = file.type === 'video/mp4'
          if (!isMP4) {
            this.$alert('图片的格式暂时仅支持mp4格式哦～', '提示', {
              confirmButtonText: '确认',
              type: 'warning'
            })
            return
          }
          resolve({
            width: '',
            height: ''
          })
        } else {
          this.$alert('请上传正确格式的文件', '提示', {
            confirmButtonText: '确认',
            type: 'warning'
          })
          reject()
        }
      })
    },

    uploadfile() {
      window.document.getElementById(`videoIdx${this.tabName}`).click()
    },

    // 获取编辑数据
    fetchData(id) {
      getEditData(id).then(re => {
        const { data } = re
        this.form = Object.assign(this.form, data)
        this.content = this.form.content
        this.productSpecs = this.form.productSpecs
        this.picture.imgUrl = this.form.picture
        this.content.forEach((item) => {
          if (!item.activityType) item.activityType = 'PRODUCT'
          item.imgData = {
            myId: Math.random(),
            path: 'category',
            imgUrl: item.imageUrl,
            ImgSize: 10000,
            text: '图片大小不得超过10000K，支持png/jpg格式'
          }
          item.imgData2 = {
            myId: Math.random(),
            path: 'category',
            imgUrl: item.phoneImg,
            ImgSize: 10000,
            text: '图片大小不得超过10000K，支持png/jpg格式'
          }
          item.videoContent = ''
          if (item.style.detailsLayout === 'VIDEO_ALL') {
            item.videoContent = `<div>
                    <video
                      controls
                      x5-playsinline playsinline webkit-playsinline
                      poster="/${item.imageUrl}"
                      class="video_upload_con"
                      object-fit: fill" >
                        <source src="${item.videoUrl}" type="video/mp4" />
  		                  您的浏览器不支持video标签播放视频
                    </video>
                </div>`
          }
        })
        this.productSpecs.forEach((item) => {
          item.pictureUrl = {
            myId: Math.random(),
            path: 'category',
            imgUrl: item.picture,
            ImgSize: 10000,
            text: '图片大小不得超过10000K，支持png/jpg格式'
          }
        })
      })
    },

    getCategoryList() {
      getCategoryList().then(re => {
        this.categoryList = re.data
      })
    },

    getSpecLabel() {
      getSpecLabel().then(re => {
        this.specLabel = re.data
      })
    },

    /**
     * 保存、发布接口
     *
     * id：保存为空，编辑传列表id
     */
    submitForm(status) {
      if (this.ajaxStatus) {
        return
      }
      this.ajaxStatus = true

      const errorText = this.validateForm()
      if (errorText) {
        this.ajaxStatus = false
        this.$message.error(errorText)
        return
      }
      this.form.content = this.content
      this.form.productSpecs = this.productSpecs
      this.form.picture = this.picture.imgUrl
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.status = status
          postData(this.form)
            .then(re => {
              this.ajaxStatus = false
              this.$notify({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.reset()
            })
            .catch(() => {
              this.ajaxStatus = false
            })
        } else {
          this.ajaxStatus = false
          this.$message.error('请正确填写完整信息后再发布')
          return false
        }
      })
    },

    resetActivityType(idx) {
      this.$set(this.content[idx], 'detailLink', '')
      this.$set(this.content[idx], 'buyLink', [{
        name: '',
        buyPlatformColor: '#000',
        link: ''
      }])
    },

    reset() {
      // 编辑发布后直接关闭tab跳转至列表页面
      if (+this.tabName > 2) {
        this.$emit('removeTab', this.tabName, '1')
        return
      }
      this.form = Object.assign({}, defaultForm)
      this.$refs['form'].resetFields()
      this.content = [{
        title: '',
        subTitle: '',
        imgData: {
          myId: Math.random(),
          path: 'product',
          imgUrl: '',
          ImgSize: 10000,
          text: '图片大小不得超过10000K，支持png/jpg格式'
        },
        imgData2: {
          myId: Math.random(),
          path: 'product',
          imgUrl: '',
          ImgSize: 10000,
          text: '图片大小不得超过10000K，支持png/jpg格式'
        },
        imageUrl: '',
        description: '',
        detailLink: '',
        buyLink: [{
          name: '',
          buyPlatformColor: '#000',
          link: ''
        }],
        style: {
          detailsLayout: 'PIC_LEFT',
          status: 1,
          styleName: '',
          titleColor: '#000',
          subTitleColor: '#000',
          descriptionColor: '#000'
        }
      }]
      this.productSpecs = [{
        alw: 0,
        labelId: '',
        text: '',
        desc: '',
        picture: '',
        pictureUrl: {
          myId: Math.random(),
          path: 'product',
          imgUrl: '',
          ImgSize: 10000,
          text: '图片大小不得超过10000K，支持png/jpg格式'
        }
      }]
      this.$emit('removeTab', this.tabName)
    },

    /**
       * 验证表单项
       * @returns {string} 错误提示
       */
    validateForm() {
      var errorText = ''
      this.content.forEach(item => {
        if (item.title && item.title.length > 60) {
          errorText = '请输入小于60个字符的标题'
        } else if (item.subTitle && item.subTitle.length > 60) {
          errorText = '请输入小于60个字符的副标题'
        } else if (item.style.detailsLayout !== 'PIC_NO' && item.style.detailsLayout !== 'VIDEO_ALL' && (!item.imgData.imgUrl || !item.imgData2.imgUrl)) {
          errorText = '请输入上传图片'
        } else if (item.description && item.description.length > 200) {
          errorText = '请输入小于200个字符的标题'
        }
        if (item.style.detailsLayout !== 'PIC_NO' && item.style.detailsLayout !== 'VIDEO_ALL') {
          item.imageUrl = item.imgData.imgUrl
          item.phoneImg = item.imgData2.imgUrl
        }
      })
      this.productSpecs.forEach(item => {
        if (!item.labelId) {
          errorText = '请选择规格名称'
        }
        item.picture = item.pictureUrl.imgUrl
      })
      return errorText
    }
  }
}
</script>
<style lang="scss">
.href-remark{
  color: #5e6d82;
  .red {
    background-color: #fdf6ec;
    color: #e6a23c;
  }
}
.logo-card{
  margin-bottom: 10px;
}
.video_upload_con{
  height: 100px;
  width: auto;
}
</style>

